




package com.crm.manager.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.manager.domain.Activity;
import com.crm.manager.domain.dto.ActivityDto;
import com.crm.manager.domain.vo.PageVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.crm.manager.mapper.ActivityMapper;
import com.crm.manager.service.IActivityService;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

/**
 * 活动Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-01
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper,Activity> implements IActivityService {
    @Autowired
    private ActivityMapper activityMapper;

    @Override
    public void addActivity(ActivityDto activityDto) {
        Activity activity = new Activity();
        BeanUtils.copyProperties(activityDto, activity);
        activity.setCode(addActivity(activity));
        activity.setBeginTime(activity.getBeginTime());
        activity.setEndTime(activity.getEndTime());
        //如果type为“1”，则设置折扣为pt
        if (activity.getType().equals("1")) {
            activity.setDiscount(activityDto.getDiscount());
        }
        //如果type为“2”，则设置代金券为vouchers
        if (activity.getType().equals("2")) {
            activity.setVouchers(activityDto.getVouchers());
        }
//        //如果在BeginTime之前，则设置状态为待审核（"1"）
//        if (activity.getBeginTime().isBefore(activityDto.getBeginTime())) {
//            activity.setStatus("1");
//        }
//        //如果在BeginTime和EndTime之间，则设置状态为已通过（"2"）
//        if (activity.getBeginTime().isAfter(activityDto.getBeginTime()) && activity.getBeginTime().isBefore(activityDto.getEndTime())) {
//            activity.setStatus("2");
//        }
//        //在EndTime之后，则设置状态为已结束（"4"）
//        if (activity.getEndTime().isAfter(activityDto.getEndTime())) {
//            activity.setStatus("4");
//        }
        activity.setCreateTime(LocalDateTime.now());
        activityMapper.add(activity);
    }

    @Override
    public PageVO page(ActivityDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<Activity> list = activityMapper.page(dto);
        Page<Activity> page = (Page<Activity>) list;
        long total = page.getTotal();
        PageVO pageVO = new PageVO();
        pageVO.setTotal(total);
        pageVO.setRows(page.getResult());
        return pageVO;
    }

    @Override
    public Activity getById(Integer id) {
        Activity activity = activityMapper.getById(id);
        return activity;
    }

    @Override
    public int delete(Integer[] ids) {
       return activityMapper.delete(ids);
    }

    @Override
    public List<Activity> listselect(Integer channel) {
        return activityMapper.listselect(String.valueOf(channel));
    }

    @Override
    public void update(Activity activity) {
        activityMapper.update(activity);
    }

    @Override
    public String getDiscountTypeById(Integer activityId) {
        return activityMapper.getDiscountTypeById(activityId);
    }


    public String addActivity(Activity activity) {
        String code;
        int maxAttempts = 10; // 最多尝试生成 10 次 code
        int attempts = 0;

        do {
            code = CodeGenerator.generateRandomCode(); // 生成随机 code
            attempts++;
            if (attempts > maxAttempts) {
                throw new RuntimeException("无法生成唯一的活动代码，请稍后重试！");
            }
        } while (activityMapper.countByCode(code) > 0); // 检查 code 是否已存在

        activity.setCode(code); // 设置唯一的 code
        return code;
    }



    public static class CodeGenerator {

        // 定义字符池：1-9 数字 + 小写字母 + 大写字母
        private static final String CHARACTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        private static final int CODE_LENGTH = 8; // code 的长度

        /**
         * 生成随机的 code
         *
         * @return 返回一个随机的 code
         */
        public static  String generateRandomCode() {
            Random random = new Random();
            StringBuilder code = new StringBuilder(CODE_LENGTH);
            for (int i = 0; i < CODE_LENGTH; i++) {
                int index = random.nextInt(CHARACTERS.length());
                code.append(CHARACTERS.charAt(index));
            }
            return code.toString();
        }
    }
    }


